package com.topone.testaidl;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;

import com.topone.server.ILoginAidlInterface;
import com.topone.server.UserInfo;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void doLogin(View v) {
        if (loginAidlInterface != null) {
            try {
                boolean isLoginSuccessful = loginAidlInterface.login(new UserInfo("tom", "jack"));
                if (isLoginSuccessful) {
                    Log.e("TAG", " client success!!!");
                } else {
                    Log.e("TAG", "client failed!!");
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            Intent intent = new Intent();
            //5.0之后不允许
//        intent.setAction("com.topone.server.ServerLoginService");
//        intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setComponent(new ComponentName("com.topone.testaidl", "com.topone.server.ServerLoginService"));
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }

    }

    ILoginAidlInterface loginAidlInterface = null;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            /**
             * 获取Binder,asInterface中会根据DESCRIPTOR判断是否是跨进程的Binder,如果是跨进程的Binder就封转成Proxy,如果不是,
             * 直接返回Binder
             */
            loginAidlInterface = ILoginAidlInterface.Stub.asInterface(service);
            try {
                boolean isLoginSuccessful = loginAidlInterface.login(new UserInfo("111", "2222"));
                if (isLoginSuccessful) {
                    Log.e("TAG", " client success!!!");
                } else {
                    Log.e("TAG", "client failed!!");
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            loginAidlInterface = null;
        }
    };
}
